package org.jeecg.common.util;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

public class XmlUtils {
    public static String converTomXml(Object obj) throws JAXBException {
//        return converToXml(obj,"UTF-8");
        return converToXml(obj,"gbk" , true);
    }
    public static String converTomXml(Object obj,Boolean hideHead) throws JAXBException {
//        return converToXml(obj,"UTF-8");
        return converToXml(obj,"gbk" , hideHead);
    }

    private static String formatXmlStr(Object obj, String encoding) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
//        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
        marshaller.setProperty(Marshaller.JAXB_ENCODING,encoding);
        StringWriter writerlog = new StringWriter();
        marshaller.marshal(obj, writerlog);
        return writerlog.toString();
    }
    private static String converToXml(Object obj, String encoding,Boolean hideHead) throws JAXBException {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            // 去掉生成xml的默认报文头
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, hideHead);
            // xml格式,false,不带格式，
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
//            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING,encoding);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj,writer);
            result = writer.toString();

//            System.out.println("发送数据：" + result);
//            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//            StringWriter writerlog = new StringWriter();
//            marshaller.marshal(obj,writerlog);
//            System.out.println("发送数据：" + writerlog.toString());
        } catch (Exception e) {
            throw e;
        }
        return result;
    }

    public static<T> T converyToJavaBean(String xml,Class<T> c) throws JAXBException {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T)unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            throw e;
        }
        return t;
    }

}

